/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

/*
//迭代法
  // (前序遍历)
    TreeNode* invertTree(TreeNode* root){
        if(root == nullptr) return root;
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty()){
            TreeNode* node = s.top();
            s.pop();
            swap(node->left, node->right);
            if(node->left) s.push(node->left);
            if(node->right) s.push(node->right);
        }
        return root;
    }
*/
  
  // 层序遍历
    TreeNode* invertTree(TreeNode* root){
        if(root == nullptr) return root;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            size_t size = q.size();
            for(size_t i = 0; i < size; ++i){
                TreeNode* node = q.front();
                q.pop();
                swap(node->left, node->right);
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
        }
        return root;
    }
};